<template>
  <div class="sku-editor">
    <!-- 规格属性设置 -->
    <div class="spec-section">
      <div v-for="(spec, index) in specs" :key="spec.id" class="spec-item">
        <!-- {{ spec }} -->
        <el-input v-model="spec.spec_name" placeholder="规格名称" style="width: 200px; margin-right: 10px;"></el-input>

        <el-tag v-for="value in spec.spec_value" :key="value.id" closable @close="removeSpecValue(index, value.id)">
          {{ value.spec_name }}
        </el-tag>

        <el-input v-if="spec.inputVisible" v-model="spec.inputValue" size="small" style="width: 100px;"
          @keyup.enter.native="addSpecValue(index)" @blur="addSpecValue(index)" ref="saveTagInput">
        </el-input>

        <el-button v-else size="small" @click="showInput(index)">
          + 添加规格值
        </el-button>

        <el-button type="text" style="margin-left: 10px;" @click="removeSpec(index)">
          <i class="el-icon-delete"></i> 删除
        </el-button>
        <!-- <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="removeSpec(index)"></el-button> -->
      </div>

      <el-button type="text" @click="addSpec">
        <i class="el-icon-plus"></i> 添加规格
      </el-button>
    </div>

    <!-- SKU表格 -->
    <div class="sku-table" v-if="skuList.length > 0">
      <h3>SKU列表</h3>
      <el-table :data="skuList" border style="width: 100%">
        <el-table-column v-for="(spec, index) in specs" :key="spec.id" :label="spec.spec_name" width="120">
          <template slot-scope="{row}">
            {{ spec.spec_value[index].spec_name }}
            <!-- {{ getSpecName(row.specs, spec.id) }} -->
          </template>
        </el-table-column>
        <el-table-column label="价格" width="150">
          <template slot-scope="{row}">
            <el-input-number v-model="row.price" :min="0" :precision="2" controls-position="right" size="small">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="会员价格" width="150">
          <template slot-scope="{row}">
            <el-input-number v-model="row.member_price" :min="0" :precision="2" controls-position="right" size="small">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="进货价格" width="150">
          <template slot-scope="{row}">
            <el-input-number v-model="row.buy_price" :min="0" :precision="2" controls-position="right" size="small">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="成本价" width="150">
          <template slot-scope="{row}">
            <el-input-number v-model="row.trade_price" :min="0" :precision="2" controls-position="right" size="small">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="库存" width="120">
          <template slot-scope="{row}">
            <el-input-number v-model="row.stock" :min="0" controls-position="right" size="small">
            </el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="SKU编码" width="180">
          <template slot-scope="{row}">
            <el-input v-model="row.sku_code" size="small"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="图片" width="150">
          <template slot-scope="{row}">
            <el-upload class="sku-uploader" action="/admin/common/upload" :show-file-list="false"
              :on-success="(res, file) => handleSkuImageSuccess(row, res, file)" :before-upload="beforeSkuImageUpload">
              <img v-if="row.picture" :src="row.picture" class="sku-image">
              <i v-else class="el-icon-plus sku-uploader-icon"></i>
            </el-upload>
            <!-- <Upload class="sku-uploader" :fileList.sync="row.picture" :accept="'image/*'" :limit="1" fileSize="10" :fileType="1" @update:fileList="updatePictureFileList"/> -->
          </template>
        </el-table-column>

        <el-table-column label="状态" width="180">
          <template slot-scope="{row}">
            <el-select v-model="row.status" placeholder="请选择状态">
              <el-option v-for="item in dicData" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <!-- <div class="batch-actions" style="margin-top: 15px;">
        <el-button size="small" @click="batchSetPrice">批量设置价格</el-button>
        <el-button size="small" @click="batchSetStock">批量设置库存</el-button>
      </div> -->
    </div>
  </div>
</template>

<script>
import { generateId, cartesianProduct } from '../utils/sku'
import Upload from './upload.vue'
import { getProductSkuInfo } from "../api/product";
export default {
  name: 'SkuEditor',
  components: {
    Upload
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      dicData: [{
        label: '上架',
        value: 0
      }, {
        label: '下架',
        value: 1
      }],
      specs: [
        // {
        //   id: generateId(),
        //   name: '颜色',
        //   values: [
        //     { id: generateId(), name: '红色' },
        //     { id: generateId(), name: '蓝色' }
        //   ],
        //   inputVisible: false,
        //   inputValue: ''
        // },
        // {
        //   id: generateId(),
        //   name: '尺寸',
        //   values: [
        //     { id: generateId(), name: 'S' },
        //     { id: generateId(), name: 'M' }
        //   ],
        //   inputVisible: false,
        //   inputValue: ''
        // }
      ],
      skuList: []
    }
  },
  watch: {
    specs: {
      handler () {
        this.generateSkuList()
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    // this.generateSkuList()
  },
  methods: {
    updatePictureFileList (val) {
      console.log('sku 图片', val);

    },
    // 添加规格
    addSpec () {
      console.log('添加规格:', this.specs);

      this.specs.push({
        id: '', //generateId(),
        spec_name: '',
        spec_value: [],
        inputVisible: false,
        inputValue: ''
      })
    },

    // 删除规格
    removeSpec (index) {
      this.$confirm('确定删除该规格吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.specs.splice(index, 1)
      })
    },

    // 显示规格值输入框
    showInput (index) {
      this.specs[index].inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput[index].$refs.input.focus()
      })
    },

    // 添加规格值
    addSpecValue (index) {
      console.log('添加规格值：', this.specs[index]);

      const inputValue = this.specs[index].inputValue
      if (inputValue) {
        this.specs[index].spec_value.push({
          id: '',// generateId(),
          spec_name: inputValue
        })
        this.specs[index].inputVisible = false
        this.specs[index].inputValue = ''
      }
    },

    // 删除规格值
    removeSpecValue (specIndex, valueId) {
      this.specs[specIndex].spec_value = this.specs[specIndex].spec_value.filter(
        v => v.id !== valueId
      )
    },

    // 生成SKU列表
    generateSkuList () {
      console.log('生成SKU列表:', this.specs);
      if (this.specs.length === 0 || this.specs.some(spec => spec.spec_value.length === 0)) {
        this.skuList = []
        return
      }
      let specsArr = []
      this.specs.forEach(i => {
        specsArr.push({
          name: i.spec_name,
          value: i.spec_value.map(j => { return j.spec_name })
        })
      })
      getProductSkuInfo({ spec_info: specsArr }).then((res) => {
        this.skuList = res.data.map(comb => {

          // 查找是否已存在相同的SKU组合
          const existingSku = this.skuList.find(sku => {
            console.log(120, sku, comb);

          }
            // sku.specs.length === comb.length &&
            // sku.specs.every(s =>
            //   comb.some(c => c.specId === s.specId && c.valueId === s.valueId)
            // )
          )
          return existingSku || {
            id: '',//generateId(),
            specs: comb,
            sku_code: null,
            price: null,
            member_price: null,
            buy_price: null,
            trade_price: null,
            stock: null,
            picture: null,
            status: null,
          }
        })
      }
      );

      return
      // 计算笛卡尔积
      const combinations = cartesianProduct(
        this.specs.map(spec =>
          spec.spec_value.map(value => ({
            specId: spec.id,
            valueId: value.id
          }))
        ))
      // 生成或更新SKU列表
      this.skuList = combinations.map(comb => {
        // 查找是否已存在相同的SKU组合
        const existingSku = this.skuList.find(sku =>
          sku.specs.length === comb.length &&
          sku.specs.every(s =>
            comb.some(c => c.specId === s.specId && c.valueId === s.valueId)
          )
        )

        return existingSku || {
          id: '',//generateId(),
          specs: comb,
          sku_code: null,
          price: null,
          member_price: null,
          buy_price: null,
          trade_price: null,
          stock: null,
          picture: null,
          status: null,
        }
      })
    },

    // 获取规格名称
    getSpecName (specs, specId) {
      console.log(1, '获取规格名称', specs, specId);
      const spec = specs.find(s => s.specId === specId)
      if (!spec) return ''
      const specDef = this.specs.find(s => s.id === specId)
      const value = specDef.spec_value.find(v => v.id === spec.valueId)
      return value ? value.spec_name : ''
    },

    // SKU图片上传成功
    handleSkuImageSuccess (row, res, file) {
      // 这里应该是上传到服务器后返回的图片URL
      // 模拟上传成功
      row.picture = URL.createObjectURL(file.raw)
    },

    // 上传前校验
    beforeSkuImageUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },

    // 批量设置价格
    batchSetPrice () {
      this.$prompt('请输入价格', '批量设置', {
        inputPattern: /^\d+(\.\d{1,2})?$/,
        inputErrorMessage: '价格格式不正确'
      }).then(({ value }) => {
        this.skuList.forEach(sku => {
          sku.price = parseFloat(value)
        })
      })
    },

    // 批量设置库存
    batchSetStock () {
      this.$prompt('请输入库存', '批量设置', {
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '库存必须为正整数'
      }).then(({ value }) => {
        this.skuList.forEach(sku => {
          sku.stock = parseInt(value)
        })
      })
    },

    // 获取SKU数据
    getSkuData () {
      return {
        spec_info: this.specs.map(spec => ({
          id: spec.id,
          spec_name: spec.spec_name,
          spec_value: spec.spec_value.map(j => { return j.spec_name })
        })),
        sku_info: this.skuList
      }
    },

    // 设置SKU数据（用于编辑时初始化）
    setSkuData (data) {
      console.log('用于编辑时初始化data', data);

      if (data && data.spec_info) {
        this.specs = data.spec_info.map(spec => ({
          ...spec,
          inputVisible: false,
          inputValue: ''
        }))
      }
      if (data && data.sku_info) {
        this.skuList = data.sku_info
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.spec-item {
  // margin-bottom: 15px;
  // padding: 10px;
  border: 1px dashed #eee;
  border-radius: 4px;
}

.el-tag {
  margin-right: 6px;
}

.sku-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 60px;
  height: 60px;

  .media-file {
    width: 60px;
    height: 60px;
  }
}

.sku-uploader:hover {
  border-color: #409EFF;
}

.sku-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.sku-image {
  width: 100%;
  height: 100%;
  display: block;
}

.el-tag {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409EFF;
}

::v-deep .el-tag .el-tag__close {
  color: #409EFF !important;
}

::v-deep .el-tag .el-tag__close:hover {
  color: #FFF !important;
  background-color: #409EFF;
}
</style>
